package com.dzu.medium;

/**
 * @author ZhaoDong
 * @date 2022/10/28 10:21
 * @description 43. 字符串相乘
 */
public class Test43 {

    public static void main(String[] args) {
        System.out.println(multiply("1", "2"));
    }


    //执行用时：
    //42 ms
    //, 在所有 Java 提交中击败了
    //5.70%
    //的用户
    //内存消耗：
    //41.6 MB
    //, 在所有 Java 提交中击败了
    //47.38%
    //的用户
    public static String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }


        StringBuffer res = new StringBuffer();

        for (int j = num2.length() - 1; j >= 0; j--) {
            int num2Str = num2.charAt(j) - '0';

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < num2.length() - j - 1; i++) {
                sb.append(0);
            }
            int jinwei = 0;
            for (int i = num1.length() - 1; i >= 0; i--) {
                int num1Str = num1.charAt(i) - '0';
                int sum = jinwei;
                sum += num2Str * num1Str;
                sb.append(sum % 10);
                jinwei = sum / 10;

            }
            if (jinwei > 0) {
                sb.append(jinwei);
            }
            String sbStr = sb.toString();
            if (res.length() == 0) {
                res = sb;
            } else {
                int as = 0;
                StringBuffer tempSb = new StringBuffer();
                for (int i = 0, k = 0; i < res.length() || k < sbStr.length(); i++, k++) {
                    int sum = as;
                    sum += i < res.length() ? res.charAt(i) - '0' : 0;
                    sum += k < sbStr.length() ? sbStr.charAt(k) - '0' : 0;
                    tempSb.append(sum % 10);
                    as = sum / 10;
                }
                if (as > 0) {
                    tempSb.append(as);
                }
                res = tempSb;
            }

        }
        return res.reverse().toString();

    }
}
